<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 商户认证信息
 * @author khj
 */
class Certification extends MY_Controller {
    /**
     * 设置模块
     * @var AdmSettingModel
     */
    public $mSetting;

	public function __construct(){
		parent::__construct();
	}

    /**
     * 店铺类型
     */
    public function shopCategory(){
        $tA = $this->mUser->getMerchantCategory();
        $this->appReturn(1, '', $tA);
    }

    /**
     * 店铺认证
     */
    public function shopCertification(){

        //表单验证
        $vConf = array(
            array('category_id', '店铺类型', 'required|in_list[2]'),
            array('shop_name', '店铺名称', 'required'),
            array('province', '省份', 'required|is_numeric'),
            array('city', '城市', 'required|is_numeric'),
            array('county', '区县', 'required|is_numeric'),
            array('address', '详细地址', 'required'),
            array('street', '门牌号', 'required'),
            array('longitude', '经度', 'required'),
            array('latitude', '纬度', 'required'),
            array('shop_type', '消费模式', 'required|in_list[1,2,3]'),
            array('id_name', '法人姓名', 'required'),
            array('identification', '法人身份证号', 'required|valid_idcard')
        );
        $this->formDataValidation($vConf);
        $latitude = trim(post('latitude'));
        $longitude = trim(post('longitude'));
        $province = (int)post('province');
        $city = (int)post('city');
        $county = (int)post('county');
        $address = trim(post('address'));
        //是否提交过验证信息
        $info = $this->mUser->getShopInfo($this->userId);

        if(!$_FILES && !$info)$this->appReturn(0, '请上传营业执照');
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');

        $ak = $this->mSetting->get('map_key', 'deliveryman');
        $addressIds = array();
        if (!in_array($province, $addressIds)){
            $addressIds[] = $province;
        }
        if (!in_array($city, $addressIds)){
            $addressIds[] = $city;
        }
        if (!in_array($county, $addressIds)){
            $addressIds[] = $county;
        }

        $address_str = '';
        if ($addressIds){
            $this->loadModel('AdmSettingModel','mSetting','admin');
            $tAddress = $this->mSetting->getLocationNameByIds($addressIds);
            if(strpos($address,$tAddress[$province]['name']) === false){
                $address_str = $tAddress[$province]['name'];
            }
            if(strpos($address,$tAddress[$city]['name']) === false){
                $address_str .= $tAddress[$city]['name'];
            }
            if(strpos($address,$tAddress[$county]['name']) === false){
                $address_str .= $tAddress[$county]['name'];
            }
            $address_str .= $address;
        }

        if ( ! $address_str){
            $this->appReturn(0,'地址不存在');
        }

//        $url = 'http://api.map.baidu.com/geocoder/v2/?address='.$address_str.'&output=json&ak='.$ak;
//
//        $tA = $this->_request($url);
//
//        if($tA == false){
//            $this->appReturn(0, '地址解析错误');
//        }
//
//        $tS = getDistance($latitude, $longitude, $tA[0], $tA[1]);
//
//        if( ! is_numeric($tS) || $tS > 100){
//            $this->appReturn(0, '店铺地址有误差:'.$tS);
//        }

        $data = array(
            'merchant_id' => $this->userId,
            'category_id' => (int)post('category_id'),
            'shop_name' => trim(post('shop_name')),
            'province' => (int)post('province'),
            'city' => (int)post('city'),
            'county' => (int)post('county'),
            'address' => $address,
            'street' => trim(post('street')),
            'shop_type' => (int)post('shop_type'),
            'id_name' => trim(post('id_name')),
            'identification' => trim(post('identification')),
            'latitude' => $latitude,
            'longitude' => $longitude,
            'status' => 3,
            'addtime' => time()
        );

        if(isset($_FILES['license']) && $_FILES['license']){
            $path = 'uploads/'.$this->port.'/'.$this->userId.'/license';
            $tA = imageUpload($path, 'license', 'license', true, 250, 250);
            if( ! $tA['status']){
                $this->appReturn(0, '营业执照上传失败');
            }
            $data['license'] = $tA['data'];
            unset($tA);
        }
        //其他证件照
        if(isset($_FILES['id_photo']) && $_FILES['id_photo']){
            $path = 'uploads/'.$this->port.'/'.$this->userId.'/other_documents';
            $tA = imageUpload($path, 'id_photo', 'id_photo', true, 250, 250);
            if( ! $tA['status']){
                $this->appReturn(0, '营业执照上传失败');
            }
            $img[] = $tA['data'];
            $data['other_documents'] = json_encode($img);
            unset($tA);
        }

        //保存信息
        $id = isset($info['merchant_id']) ? $info['merchant_id']:0;
        if(!($this->mUser->saveShop($data, $id)) || !($this->mUser->save(array('category_id'=>$data['category_id']), $this->userId))){
            $this->appReturn(0,'保存失败');
        }

        $this->appReturn(1,'保存成功');
    }

    /**
     * 获取店铺认证信息
     */
    public function certifyInfo(){

        $info = $this->mUser->getShopInfo($this->userId);

        unset($info['mobile'],$info['portrait'],$info['sale_quantity'],$info['score'],$info['business_week']);
        unset($info['business'],$info['shop_imgs'],$info['addtime']);
        $this->appReturn(1,'', $info);
    }

    /**
     * 请求接口
     *
     * @param	string	$url	请求路径
     * @param 	array 	$param	请求参数
     */
    public function _request($url){

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, false);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        $data = curl_exec($curl);
        if(curl_errno($curl)){
            p(curl_error($curl));
            exit(array('status' => 0, 'data' => NULL, 'message' => curl_error($curl)));
        }
        curl_close($curl);
        $tA = json_decode($data, true);
        if( ! is_array($tA) || ! isset($tA['status']) || $tA['status'] != 0){
            return false;
        }

        return [$tA['result']['location']['lat'], $tA['result']['location']['lng']];
    }


}